package com.hua.yuan.live.repertory.cloud_data.loader;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hua.yuan.common.https.OkHttpModule;
import com.hua.yuan.live.repertory.cloud_data.JsonResult;
import com.hua.yuan.live.repertory.cloud_data.api.LiveSearchIndexApi;
import com.hua.yuan.live.repertory.cloud_data.res.RoomBean;

import java.io.IOException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

/**
 * 直播搜索的页面
 */
public class LiveSearchIndexLoader extends AsyncTaskLoader<List<RoomBean>> {

    private String mToken;
    private String mSlug;

    private List<RoomBean> mTargetData;

    public LiveSearchIndexLoader(Context context) {
        super(context);
    }

    @Override
    public List<RoomBean> loadInBackground() {
        LiveSearchIndexApi searchIndexApi= OkHttpModule.getInstance().getRetrofit().create(LiveSearchIndexApi.class);
        Call<String> call=searchIndexApi.searchIndex(mToken,mSlug);
        try {
            Response<String> response = call.execute();
            if(response.body()==null || response.body().equals("")){
                return null;
            }
            JsonResult<JSONArray> resultData= JSONObject.parseObject(response.body(),JsonResult.class);
            if(resultData==null){
                return null;
            }
            JSONArray array=resultData.getData();
            List<RoomBean> targetData = JSONObject.parseArray(array.toJSONString(),RoomBean.class);
            if(targetData==null){
                return null;
            }
            mTargetData=targetData;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mTargetData;
    }

    /**
     * 请求数据源
     * @param pToken
     * @param pSlug
     */
    public void requestData(String pToken,String pSlug){
        this.mToken=pToken;
        this.mSlug=pSlug;
        forceLoad();
    }
}
